package com.example.zg3_park.news

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil.ItemCallback
import androidx.recyclerview.widget.RecyclerView.ViewHolder

import com.example.lib_base.entity.NewsEntityItem
import com.example.zg3_park.R
import com.example.zg3_park.databinding.ItemNewsBinding


class NewsAdapter:PagingDataAdapter<NewsEntityItem, NewsAdapter.NewsViewHolder>(diff) {

    private var mOnItemLongClickListener: OnItemLongClickListener? = null
    private var mOnItemClickListener: OnItemClickListener? = null

    companion object{
        val diff = object :ItemCallback<NewsEntityItem>() {
            override fun areItemsTheSame(
                oldItem: NewsEntityItem,
                newItem: NewsEntityItem
            ): Boolean {
                return oldItem == newItem
            }

            override fun areContentsTheSame(
                oldItem: NewsEntityItem,
                newItem: NewsEntityItem
            ): Boolean {
                return oldItem.id == newItem.id
            }

        }
    }

    class NewsViewHolder(view: View):ViewHolder(view) {
        val binding = DataBindingUtil.bind<ItemNewsBinding>(view)
    }

    override fun onBindViewHolder(holder: NewsViewHolder, position: Int) {
        holder.binding?.news = getItem(position)

        val item = getItem(position)
        holder.binding?.news = item
        holder.itemView.setOnClickListener {
            this.mOnItemClickListener?.onItemClick(position,item!!)
            return@setOnClickListener
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NewsViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_news, parent, false)
        return NewsViewHolder(view)
    }

    fun setOnItemClickListener(listener: OnItemClickListener?) {
        this.mOnItemClickListener = listener
    }

    fun setOnItemLongClickListener(listener: OnItemLongClickListener?) {
        this.mOnItemLongClickListener = listener
    }

}

interface OnItemClickListener {
    fun onItemClick(position: Int,item: NewsEntityItem)
}

interface OnItemLongClickListener {
    fun onItemLongClick(item: NewsEntityItem): Boolean
}

